//
//  APHomeBallAlertController.m
//  AqualPolo
//
//  Created by dong on 2024/5/14.
//

#import "APHomeBallAlertController.h"
#import "APHomeBallAlertView.h"
#import "APHomeDataManager.h"
#import "APPublishWorksViewController.h"
#import "APUnlockAlertViewController.h"
#import "APCoinShopController.h"
#import "VideoRecorderController.h"
#import "APVideoDataManager.h"
#import "APLoginManager.h"
#import <AVFoundation/AVFoundation.h>

@interface APHomeBallAlertController ()
@property (nonatomic, strong) APHomeBallAlertView *mainView;
@property (nonatomic, assign) bool isResult;
@end

@implementation APHomeBallAlertController

- (APHomeBallAlertView *)mainView{
    if (!_mainView) {
        _mainView = [[APHomeBallAlertView alloc] init];
        [_mainView.clickButton addTarget:self action:@selector(clickButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];

    }
    return _mainView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = LYRGBColor(10, 24, 69);
    _isResult = false;
    [self.view addSubview:self.mainView];
    [self.mainView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.view);
        make.left.equalTo(self.view).offset(30);
        make.right.equalTo(self.view).offset(-30);
    }];
    [self reloadData];
}

- (void)clickButtonDidClick:(UIButton *)sender{
    if (_isResult) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(ballUnlockSuccess:)]) {
            [self.delegate ballUnlockSuccess:self.ballType];
        }
        [self dismissViewControllerAnimated:true completion:nil];
        return;
    }
    if (_ballType == 1) {
        [self dismissViewControllerAnimated:true completion:nil];
    }else if (_ballType == 2) {
        APPublishWorksViewController *publishVC = [[APPublishWorksViewController alloc] init];
        publishVC.isCheck = true;
        [publishVC setPublishCallBack:^(bool res, NSString * _Nullable msg) {
            [self reloadDataWithSuccessUnlock];
        }];
        [self presentViewController:publishVC animated:true completion:nil];
    }else if (_ballType == 3) {
        if (![APAuthorizationManager canUseCaptureDevice]) {
            [self.view ShowProgressOnlyLabel:@"You have not authorised this permission."];
            return;
        }
        AVAuthorizationStatus Status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
        if (Status == AVAuthorizationStatusRestricted || Status == AVAuthorizationStatusDenied) {
            [self.view ShowProgressOnlyLabel:@"You have not authorised this permission."];
            return;
        }
        VideoRecorderController *videoRecorderVC = [[VideoRecorderController alloc] init];
        [videoRecorderVC recordVideoFinishedBlock:^(NSURL *fileUrl, NSString *fileName) {
            LYLog(@"==========%@==%@",fileUrl,fileName);
            [self saveVideoFile:fileName videoURL:fileUrl];
        }];
        [self presentViewController:videoRecorderVC animated:true completion:nil];
    }else{
        [self.view ShowProgress];
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        [parameters setNullObject:@(99) forKey:@"outlay"];
        [parameters setNullObject:@"iap" forKey:@"source"];
        [APDataManager postJsonWithUrlString:reviewModeConsume timeoutInterval:0 parameters:parameters result:^(NSDictionary * _Nullable res) {
            [self.view removeProgress];
            [self reloadDataWithSuccessUnlock];
        } failBlock:^(NSString * _Nullable errorMsg) {
            [self.view ShowProgressOnlyLabel:errorMsg];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                APCoinShopController *coinVC = [[APCoinShopController alloc] init];
                coinVC.autoBack = true;
                [self presentViewController:coinVC animated:true completion:nil];
            });
        }];
    }
}

- (void)reloadDataWithSuccessUnlock{
    _isResult = true;
    NSString *ballImageName = [BaseDataManager ballImageName:_ballType];
    self.mainView.ballImageView.image = [UIImage imageNamed:ballImageName];
    NSString *ballName = [BaseDataManager ballName:_ballType];
    self.mainView.ballNameLabel.text = [NSString stringWithFormat:@"【%@】",ballName];
    self.mainView.contentLabel.text = @"Congratulations on successfully unlocking the pendant and obtaining the title.";
    [self.mainView.clickButton setTitle:@"OK" forState:UIControlStateNormal];
    self.mainView.msgLabel.hidden = true;
    self.mainView.bubbleView.hidden = true;
    [[APHomeDataManager shareInstance] unlockBall:_ballType];

}

- (void)saveVideoFile:(NSString *)videoName videoURL:(NSURL *)videoURL{
    [self.view ShowProgress];
    /// 网络地址    /// 本地文件
    NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:videoURL options:opts];
    NSParameterAssert(asset);//断言
    AVAssetImageGenerator *assetImageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetImageGenerator.appliesPreferredTrackTransform = YES;
    assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
    NSError *error = nil;
    CGImageRef thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(0, 1) actualTime:NULL error:&error];
    if( error ) {
        NSLog(@"%@", error );
    }
    UIImage *image = nil;
    if(thumbnailImageRef) {
        image =  [[UIImage alloc]initWithCGImage:thumbnailImageRef];
    }
    NSString *imageName = [BaseDataManager saveImageWithData:image toFile:images_path imageName:[NSString stringWithFormat:@"%d",arc4random() % 100]];
    APVideoModel *model = [[APVideoModel alloc] init];
    APUserModel *userModel = [[APLoginManager shareInstance] userInfo];
    model.userId = userModel.userId;
    model.avatar = userModel.avatarUrl;
    model.nickname = userModel.nickname;
    model.isCreate = YES;
    model.mediaUrl = videoName;
    model.middleThumbUrl = imageName;
//    model.content = content;
//    model.title = title;
    model.isBlack = NO;
    WS(ws);
    [[APVideoDataManager shareInstance] initVideoData:^(NSArray * _Nonnull videos) {
        [[APVideoDataManager shareInstance] addVideo:model];
        [ws.view removeProgress];
        [self reloadDataWithSuccessUnlock];
    }];
}

- (void)reloadData{
    NSString *ballImageName = [BaseDataManager ballImageName:_ballType];
    self.mainView.ballImageView.image = [UIImage imageNamed:ballImageName];
    NSString *ballName = [BaseDataManager ballName:_ballType];
    self.mainView.ballNameLabel.text = [NSString stringWithFormat:@"【%@】",ballName];
    if (_ballType == 1) {
        self.mainView.contentLabel.text = [NSString stringWithFormat:@"🎉 Congratulations! Your first login is successful! 🚀As our new member, we have prepared pendant decoration and \"%@\" title as gifts for you. Thank you for joining us and let’s start this wonderful journey together! 🎁",ballName];
        [self.mainView.clickButton setTitle:@"OK" forState:UIControlStateNormal];
        self.mainView.msgLabel.text = @"You can go to the homepage to view moreother pendants.";
    }else{
        [self.mainView.clickButton setTitle:@"To unlock" forState:UIControlStateNormal];
        self.mainView.contentLabel.text = [APHomeDataManager ballIntro:_ballType];
        if (_ballType == 2) {
            self.mainView.msgLabel.text = @"You can unlock it by publishing an article.";
        }else if (_ballType == 3){
            self.mainView.msgLabel.text = @"You can unlock it by publishing a video.";

        }else{
            self.mainView.msgLabel.text = @"You need to spend 99 golds coins to unlock this pendant and title.";
            self.mainView.bubbleView.hidden = false;
        }
    }
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [super touchesEnded:touches withEvent:event];
    [self dismissViewControllerAnimated:true completion:nil];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        self.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        self.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    }
    return self;
}

@end



